<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" placeholder="请填写部门名称" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" placeholder="请填写部门编码" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门简介" prop="introduce">
      <el-input v-model="form.introduce" placeholder="请填写详细信息" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="AddOrEdit">确定</el-button>
      <el-button @click="doCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  addDepartments,
  getDepartmentSimple,
  getDepartmentDetail,
  updateDepartmentDetail
} from '@/api/departments'
export default {
  props: {
    originList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    // 自定义检验规则函数
    const existCodeValid = (rule, value, callback) => {
      //  验证编码value在所有的部门是否存在
      let existCodeList = this.originList.map(item => item.code)
      // 确认是否是编辑状态
      if (this.isEdit) {
        // 根据id 将当前编辑的部门id 从所以的部门中移除
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      console.log(existCodeList, 'existCodeList')
      if (existCodeList.includes(value)) {
        // 存在,效验失败
        callback(new Error(`部门编码${value}已存在`))
      } else {
        // 不存在, 放行 callback()
        callback()
      }
    }
    // 自定义名称效验规则
    const existNameValid = (rule, value, callback) => {
      //  验证输入部门名称value在同级不能重复
      const existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log(existNameList, 'existNameList')
      // 是否是编辑状态
      // 确认是否是编辑状态
      if (this.isEdit) {
        // 根据id 将当前编辑的部门id 从所以的部门中移除
        const pid = this.originList.find(item => item.id === this.id).pid // 获取pid
        const brothers = this.originList.filter(item => item.pid === pid) // 把所有pid相同的兄弟包装一起
        brothers.filter(item => item.id !== this.id).map(item => item.name) // 排除自己
      }
      // 如果包含这个名称
      if (existNameList.includes(value)) {
        // 存在,效验失败
        callback(new Error(`部门名称${value}已存在`))
      } else {
        // 不存在, 放行 callback()
        callback()
      }
    }

    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      list: [],
      // 检验规则对象 指定 el-form必填 指定prop检验
      rules: {
        name: [
          { required: true, message: '请输入部门的名称', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的部门名称', trigger: 'blur' },
          { validator: existNameValid, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门的编码', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入长度是1~50的部门编码', trigger: 'blur' },
          { validator: existCodeValid, trigger: 'blur' }],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '请输入部门的介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入长度是1~300的部门名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    id: function(new_val, old_val) {
      console.log(new_val, old_val)
      this.loadDepartmentDetail()
    }
  },
  created() {
    this.loadDepartment()
    if (this.isEdit) this.loadDepartmentDetail()
  },
  methods: {
    async doAdd() {
      const res = await addDepartments({ ...this.form, pid: this.id })
      console.log(res)
      this.$emit('success')
    },
    async doEdit() {
      const res = await updateDepartmentDetail(this.form)
      console.log(res)
      this.$emit('success')
    },
    doCancel() {
      this.$emit('close')
    },
    resetForm() {
      this.$refs.deptForm.resetFields() // 清空表单
    },

    AddOrEdit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    async loadDepartment() {
      const res = await getDepartmentSimple()
      console.log(res)
      this.list = res.data
    },
    async loadDepartmentDetail() {
      const res = await getDepartmentDetail(this.id)
      console.log(res)
      this.form = res.data
    }
  }
}
</script>

<style>
</style>
